﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using Rotempco.Website.Objects;
using Rotempco.Core.Logic;
using Rotempco.BaseClass.Settings;

namespace Rotempco.Website
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {

        }

        protected void Session_Start(object sender, EventArgs e)
        {
            SetSettings();

            // TODO: Debug translation helper:
            SessionStore.Instance.DebugText = false;
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            // Forward http to https:
            //if (!Request.IsSecureConnection && !Request.Url.DnsSafeHost.ToLower().Contains("localhost"))
            //{
            //    string path = string.Format("https{0}", Request.Url.AbsoluteUri.Substring(4));
            //    Response.Redirect(path);
            //}

            System.Web.HttpContext httpContext = HttpContext.Current;
            String currentURL = httpContext.Request.Url.PathAndQuery;

            if (currentURL.ToLower() == "/admin/")
                Response.Redirect("/Admin/Login/AdministratorLogin.aspx");

            if (currentURL.ToLower() == "/")
                Response.Redirect("/Default.aspx"); //TODO: Change to public start page

            if (currentURL.ToLower().Contains("/css/")
                || currentURL.ToLower().Contains("/services/")
                || currentURL.ToLower().Contains("/scripts/")
                || currentURL.ToLower().Contains("/images/")
                || currentURL.ToLower().Contains("/usercontrols/")
                || currentURL.ToLower().Contains("/masterpages/")
                || currentURL.ToLower().Equals("/")
                || currentURL.ToLower().Equals("/default.aspx")
                )
                return;

            string newUrl = currentURL.Replace("/WebPages", "").Replace("/Public", "");

            // Department || Admin || none:

            string firstDirectory = newUrl.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();

            if (firstDirectory.ToLower() == "admin")
            {
                newUrl = StringLogic.ReplaceString(newUrl, "/admin/", "/", StringComparison.InvariantCultureIgnoreCase);

                if (newUrl == "/" || newUrl == "/default.aspx")
                    newUrl = "/"; //TODO: Change default admin page

                newUrl = "/Admin" + newUrl;
            }
            else
            {
                // Default page:
                if (newUrl == "/" || newUrl == "/Default.aspx")
                    newUrl = "/"; //TODO: Change to public start page

                newUrl = "/Public" + newUrl;
            }

            if (newUrl.EndsWith("/"))
                newUrl += "Default.aspx";

            newUrl = "/WebPages" + newUrl;

            httpContext.RewritePath(newUrl);

        }

        protected void Application_EndRequest(object sender, EventArgs e)
        {
            CoreSetup.ClearCache();
        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }

        void Application_AcquireRequestState(object sender, EventArgs e)
        {
            if (HttpContext.Current.Session != null)
            {
                SetSettings();
            }
        }

        private static void SetSettings()
        {
            if (SessionStore.Instance.SingletonCacheObject == null)
                SessionStore.Instance.SingletonCacheObject = CoreSetup.GetNewCache();

            CoreSetup.SetCache(SessionStore.Instance.SingletonCacheObject);
            CoreSetup.SetSettings();

            string url = HttpContext.Current.Request.Url.LocalPath.ToLower();
            if (url.StartsWith("/webpages/public/") || url.StartsWith("/services/public/"))
            {
                SessionStore.Instance.Clear();
                CoreSettingsLogic.SetSymmetricEncryptionKey(PublicSessionStore.Instance.PublicUserKeyHash);
            }
            else if (url.StartsWith("/webpages/admin/") || url.StartsWith("/services/admin/"))
            {
                PublicSessionStore.Instance.Clear();
            }
            else
                throw new Exception("Unknown path");
        }
    }
}